package com.qsmx.qingqiuticket.app.delegate;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qsmx.core.delegates.AtmosDelegate;
import com.qsmx.core.net.HttpHelper;
import com.qsmx.core.net.callback.IError;
import com.qsmx.core.net.callback.IFailure;
import com.qsmx.core.net.callback.ISuccess;
import com.qsmx.core.util.ClickUtil;
import com.qsmx.core.util.CountDownTimerUtil;
import com.qsmx.core.util.StringUtil;
import com.qsmx.core.util.dialog.DialogUtil;
import com.qsmx.core.util.loader.AtmosLoader;
import com.qsmx.core.util.storage.AtmosPreference;
import com.qsmx.qingqiuticket.app.R;
import com.qsmx.qingqiuticket.app.databinding.DelegatePackageListBinding;
import com.qsmx.qingqiuticket.app.delegate.adapter.PackageListAdapter;
import com.qsmx.qingqiuticket.app.entity.AdvEntity;
import com.qsmx.qingqiuticket.app.entity.PackageListEntity;
import com.qsmx.qingqiuticket.app.event.CheckTicketWaringEvent;
import com.qsmx.qingqiuticket.app.fusion.FusionCode;
import com.qsmx.qingqiuticket.app.fusion.FusionData;
import com.qsmx.qingqiuticket.app.fusion.FusionPre;
import com.qsmx.qingqiuticket.app.net.HttpUrl;
import com.qsmx.qingqiuticket.app.util.CameraManager;
import com.qsmx.qingqiuticket.app.util.SoundPlayUtils;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Type;

public class PackageListDelegate extends AtmosDelegate {
    private CountDownTimerUtil timer;
    private PackageListAdapter adapter;
    private DelegatePackageListBinding mBinding;

    @Override
    public Object setLayout() {
        return R.layout.delegate_package_list;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        startCountDownTime(60);
        initData();
        SoundPlayUtils.play(1);

        mBinding = DelegatePackageListBinding.bind(rootView);
        mBinding.tvBackHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtil.isNotFastClick()) {
                    getSupportDelegate().pop();
                }
            }
        });

        mBinding.clLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ClickUtil.isNotFastClick()) {
                    getSupportDelegate().start(new HomeLoginMemDelegate());
                }
            }
        });

        adapter = new PackageListAdapter(getContext());
        mBinding.rlvPackageList.setAdapter(adapter);
        mBinding.rlvPackageList.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter.setonItemClickListener(new PackageListAdapter.OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                if (ClickUtil.isNotFastClick()) {
                    int ticketNum = 0;
                    for (PackageListEntity.BodyBean.ChildrenMachineStorePackageItemRespsBean data : adapter.getData().get(position).getChildrenMachineStorePackageItemResps()) {
                        if (data.getType().equals("1")) {
                            ticketNum++;
                        }
                    }
                    if (ticketNum > 0) {
                        getSupportDelegate().start(SessionListDelegate.create(adapter.getData().get(position).getId(), adapter.getData().get(position).getPackageName(),
                                adapter.getData().get(position).getPackagePrice(), ticketNum, adapter.getData().get(position).isShowSessionDesc()));
                    } else {
                        long orderNoTime = System.currentTimeMillis();
                        String orderNo = "SP" + AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM) + orderNoTime + StringUtil.getRandomNumString(6);

                        getSupportDelegate().start(OrderPayDelegate.create(orderNo,
                                adapter.getData().get(position).getId(),
                                "",
                                adapter.getData().get(position).getPackagePrice(),
                                1, "",
                                "",
                                "0",
                                "0"
                        ));
                    }
                }
            }
        });
    }

    private void initData() {

        DialogUtil.showLoadingDialog(requireContext(), "正在获取套餐列表...");
        JSONObject params = new JSONObject();
        params.put("cashierNo", AtmosPreference.getCustomStringPre(FusionPre.STORE_NUM) + "-" + AtmosPreference.getCustomStringPre(FusionPre.MACHINE_NUM));
        params.put("pageNum", 1);
        params.put("pageSize", 1000);

        HttpHelper.RestClientPostRaw(params, HttpUrl.GET_PACKAGE_LIST,
                new ISuccess() {
                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void onSuccess(int code, String response) {
                        DialogUtil.dismissLoadingDialog();
                        try {
                            Type type = new TypeToken<PackageListEntity>() {
                            }.getType();
                            Gson gson = new Gson();
                            PackageListEntity mData = gson.fromJson(response, type);
                            if (mData.getHeader().getCode().equals(FusionCode.SUCCESS)) {
                                if (mData.getBody() != null && !mData.getBody().isEmpty()) {
                                    adapter.setData(mData.getBody());
                                    adapter.notifyDataSetChanged();
                                }
                            } else {
                                DialogUtil.showCardErrorDialog(getContext(), mData.getHeader().getMessage(), "确定");
                            }
                        } catch (Exception e) {
                            DialogUtil.showCardErrorDialog(getContext(), e.getMessage(), "确定");
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        DialogUtil.dismissLoadingDialog();
                        DialogUtil.showCardErrorDialog(getContext(), msg, "确定");
                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {
                        DialogUtil.dismissLoadingDialog();
                        DialogUtil.showCardErrorDialog(getContext(), getString(R.string.un_know_net_error), "确定");
                    }
                });
    }

    private void startCountDownTime(final long time) {
        if (timer != null) {
            timer.cancel();
        }
        timer = new CountDownTimerUtil(time * 1000, 1000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                mBinding.tvBackHome.setText(String.format(getString(R.string.back_home), String.valueOf(millisUntilFinished / 1000)));
            }

            @Override
            public void onFinish() {
                getSupportDelegate().popTo(HomeDelegate.class, false);
            }
        };
        timer.start();// 开始计时
    }


    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        startCountDownTime(60);
        if (FusionData.mMemData != null) {
            mBinding.tvMemInfo.setText(StringUtil.getPhoneNum(FusionData.mMemData.getPhone()));
        }
    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    public void onDestroy() {
        if (timer != null) {
            timer.cancel();
        }
        super.onDestroy();
        FusionData.mMemData = null;
        DialogUtil.dismissLoadingDialog();
        DialogUtil.dismissErrorDialog();
    }
}
